package com.autotau;

import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;

public class AuthManager
{
    public enum LoginStatus
    {
      /// <summary>
      /// Logged in successfully
      /// </summary>
      Success,
      /// <summary>
      /// Bad username/password combination
      /// </summary>
      BadUsernameOrPassword,
      /// <summary>
      /// Unknown server response
      /// </summary>
      UnknownServerResponse,
      /// <summary>
      /// Authentication server is unreachable
      /// </summary>
      Unreachable,
      /// <summary>
      /// No status
      /// </summary>
      None,
    }

    public static LoginStatus login(String username, String password, int numAttempts)
    {
      for(int attempts = 1; attempts <= numAttempts; attempts++)
      {
        try
        {
          URL url = new URL("https://vwism.tau.ac.il/login.html");
          URLConnection conn = url.openConnection();

          if (conn instanceof HttpURLConnection)
          {
            ((HttpURLConnection) conn).setRequestMethod("POST");
          }

          conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          conn.setDoOutput(true);
          conn.setConnectTimeout(1000 * attempts);
          conn.setReadTimeout(1000 * attempts);

          String requestStr = String.format("buttonClicked=4&err_flag=0&err_msg=&info_flag=0&info_msg=&redirect_url=&username=%s&password=%s",
                                            username,
                                            password);

          OutputStreamWriter wd = new OutputStreamWriter(conn.getOutputStream());
          try
          {
            wd.write(requestStr);
          }
          finally
          {
            wd.close();
          }

          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          StringBuffer sb = new StringBuffer();
          try
          {
            String line;
            while ((line = rd.readLine()) != null)
              sb.append(line);
          }
          finally
          {
            rd.close();
          }

          String requestResult = sb.toString();

          // Test the server's response
          if (requestResult.contains("Login Successful") ||
              requestResult.contains("You are already logged in. No further action is required on your part."))
          {
            // Login successful
            return LoginStatus.Success;
          }

          if (requestResult.contains(
              "<INPUT TYPE=\"hidden\" NAME=\"err_flag\" SIZE=\"16\" MAXLENGTH=\"15\" VALUE=\"1\">"))
          {
            // Bad username or password
            return LoginStatus.BadUsernameOrPassword;
          }

          // Unknown server response
          return LoginStatus.UnknownServerResponse;
        }
        catch (Exception e)
        {
          Log.e("AutoTau", "Error sending auth request: " + e.getMessage());
        }
      }

      return LoginStatus.Unreachable;
    }
}
